#include "server.h"
#include "ui_server.h"

#include "client.h"

Server::Server(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Server)
{
    ui->setupUi(this);

    this->setWindowTitle("服务器端");
    this->move(100, 200);

    Client *c = new Client;
    c->show();
    c->move(900, 200);

    // 1. 创建服务器，并监听固定端口
    this->server = new QTcpServer(this);
    this->server->listen(QHostAddress::Any, 8888);

    // 3. 当有客户端连入之后，将客户端的信息显示到屏幕中
    // 当有客户端连入时，会触发 QTcpServer::newConnection 信号
    connect(this->server, &QTcpServer::newConnection, [this](){
        // nextPendingConnection(): 获取连入的客户端的socket
        this->serverSocket = this->server->nextPendingConnection();
        // 获取客户端的ip地址和端口号
        QString ip = this->serverSocket->peerAddress().toString();
        quint16 port = this->serverSocket->peerPort();

        ui->screen->setText(QString("%1:%2  已成功连入").arg(ip).arg(port));

        // 6. 接收客户端发送的数据
        // 核心：一旦客户端发送数据过来，就会触发 QTcpSocket::readyRead 信号
        //      获取客户端的数，就是从 socket 中读取内容
        connect(this->serverSocket, &QTcpSocket::readyRead, [this](){
            QByteArray buf = this->serverSocket->readAll();
            ui->screen->append(buf);
        });
    });

    // 服务器端发送数据给客户端
    connect(ui->sendBtn, &QPushButton::clicked, [this](){
        QString msg = ui->msgEdit->toPlainText();
        this->serverSocket->write(msg.toUtf8());

        ui->msgEdit->clear();
    });

    // 断开与服务器的链接
    connect(ui->disconnBtn, &QPushButton::clicked, [this](){
        this->serverSocket->disconnectFromHost();
    });
}

Server::~Server()
{
    delete ui;
}
